<script>
import { selectRoleList, addRole, updateRole, delRole, getRoleDetail, assignPerm } from '@/api/role'
import { selectPermissionList } from '@/api/permission'
import { transListToTreeData } from '@/utils'

export default {
  name: 'Role',
  data() {
    return {
      loading: true,
      showDialog: false,
      showPermDialog: false, // 权限弹出框
      currentRoleId: null, // 当前角色id 分配权限使用
      pageParm: {
        page: 1,
        pagesize: 5,
        total: 0
      },
      list: [],
      permissionList: [], // 所有权限列表
      rolePermissionList: [], // 当前角色所分配的权限列表
      formData: {
        name: '',
        description: '',
        state: 0
      },
      rules: {
        name: [
          { required: true, message: ' 角色名称不能为空', trigger: 'blur' },
          {
            validator: async(rule, value, callback) => {
              let roles = this.list
              if (this.formData.id) {
                roles = roles.filter(role => role.id !== this.formData.id)
              }
              if (roles.some(role => role.name === value)) {
                callback(new Error('存在重复的角色名称'))
              } else {
                callback()
              }
            },
            trigger: 'blur'
          }
        ],
        description: [
          { required: true, message: ' 角色描述不能为空', trigger: 'blur' },
          { min: 1, max: 100, message: '角色描述的长度为1-100个字符', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getRoleList()
  },
  methods: {
    // 自定义表格序号
    indexMethod(index) {
      return (this.pageParm.page - 1) * this.pageParm.pagesize + index + 1
    },
    // 角色列表
    async getRoleList() {
      this.loading = true
      const { rows, total } = await selectRoleList(this.pageParm)
      this.list = rows
      this.pageParm.total = total
      this.loading = false
      // 设置一个isEdit属性 用来标记行编辑状态
      this.list.forEach(item => {
        this.$set(item, 'isEdit', false)
        this.$set(item, 'editRow', {
          name: item.name,
          state: item.state,
          description: item.description
        })
      })
    },
    // 点击页数回调方法
    changePage(newPage) {
      this.pageParm.page = newPage
      this.getRoleList()
    },
    // 关闭弹窗
    close() {
      this.showDialog = false
      this.$refs.roleRef.resetFields()
    },
    // 新增角色
    addRole() {
      this.$refs.roleRef.validate(async valid => {
        if (valid) {
          await addRole(this.formData)
          this.$message.success('新增角色成功')
          this.close()
          this.getRoleList()
        }
      })
    },
    // 修改成编辑状态
    btnEdit(row) {
      row.isEdit = true
      row.editRow.name = row.name
      row.editRow.state = row.state
      row.editRow.description = row.description
    },
    // 修改角色
    async btnEditOk(row) {
      await updateRole({ ...row.editRow, id: row.id })
      // row.editRow.name = row.name  eslint错误
      Object.assign(row, { ...row.editRow, isEdit: false })
      this.$message.success('修改角色成功')
    },
    // 删除角色
    async delRole(id) {
      await delRole(id)
      // 判断是否是本页最后一个元素 是的话页码-1
      if (this.pageParm.page !== 1 && this.list.length === 1) {
        this.pageParm.page--
      }
      this.getRoleList()
      this.$message.success('删除角色成功')
    },
    // 打开权限弹窗
    async openPermDialog(id) {
      this.currentRoleId = id
      this.permissionList = transListToTreeData(await selectPermissionList(), 0)
      const { permIds } = await getRoleDetail(this.currentRoleId)
      this.rolePermissionList = permIds
      console.log(this.rolePermissionList)
      this.showPermDialog = true
    },
    // 分配权限
    async assignPerm() {
      // getCheckedKeys这个方法可以获取tree树形控件中被勾选的节点的值
      await assignPerm({ id: this.currentRoleId, permIds: this.$refs.permRef.getCheckedKeys() })
      // 这里有个小bug 必须加上下面这一行才不会出问题：就是勾选权限后点保存 然后再打开窗口取消勾选再保存 再次打开窗口后依然是勾选状态
      this.rolePermissionList = []
      this.$message.success('分配权限成功')
      this.showPermDialog = false
    }
  }
}
</script>

<template>
  <div class="container">
    <div class="app-container">
      <div class="title">
        <el-button size="mini" type="primary" @click="showDialog=true">添加角色</el-button>
      </div>
      <el-table v-loading="loading" :header-cell-style="{ background: '#f5f6f8' }" style="margin-top: 10px" border :data="list">
        <el-table-column align="left" type="index" :index="indexMethod" label="序号" width="50" />
        <el-table-column align="left" prop="name" label="角色" width="200">
          <template v-slot="{ row }">
            <el-input v-if="row.isEdit" v-model="row.editRow.name" />
            <span v-else>{{ row.name }}</span>
          </template>
        </el-table-column>
        <el-table-column align="left" prop="state" label="启用" width="200">
          <!--          #default="scope"等同于v-slot="{ row }-->
          <template #default="scope">
            <!--            :active-value="1" :inactive-value="0" 是为了让scope.row.editRow.state的值从1/0变成true/false 才能让el-switch开关生效-->
            <el-switch v-if="scope.row.isEdit" v-model="scope.row.editRow.state" :active-value="1" :inactive-value="0" />
            <span v-else>{{ scope.row.state === 1 ? '已启用' : '未启用' }}</span>
          </template>
        </el-table-column>
        <el-table-column align="left" prop="description" label="描述">
          <template v-slot="{ row }">
            <el-input v-if="row.isEdit" v-model="row.editRow.description" type="textarea" />
            <span v-else>{{ row.description }}</span>
          </template>
        </el-table-column>
        <el-table-column align="left" label="操作">
          <template v-slot="{ row }">
            <template v-if="row.isEdit">
              <el-button type="primary" size="mini" @click="btnEditOk(row)">确 认</el-button>
              <el-button size="mini" @click="row.isEdit = false">取 消</el-button>
            </template>
            <template v-else>
              <el-button type="text" @click="openPermDialog(row.id)">分配权限</el-button>
              <el-button type="text" @click="btnEdit(row)">编辑</el-button>
              <el-popconfirm style="margin-left: 10px" title="确定删除该角色吗？" @onConfirm="delRole(row.id)">
                <el-button slot="reference" type="text">删除</el-button>
              </el-popconfirm>
            </template>
          </template>
        </el-table-column>
      </el-table>
      <!--      分页插件-->
      <div style="margin-top: 40px;padding-bottom: 50px;text-align: center">
        <el-pagination
          layout="prev, pager, next"
          :page-size="pageParm.pagesize"
          :current-page="pageParm.page"
          :total="pageParm.total"
          @current-change="changePage"
        />
      </div>
    </div>
    <el-dialog title="新增角色" :visible.sync="showDialog" width="33%" @close="close">
      <el-form ref="roleRef" label-width="120px" :model="formData" :rules="rules">
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="formData.name" size="mini" style="width: 80%" />
        </el-form-item>
        <el-form-item label="启用" prop="state">
          <el-switch v-model="formData.state" />
        </el-form-item>
        <el-form-item label="角色描述" prop="description">
          <el-input v-model="formData.description" type="textarea" :rows="3" size="mini" style="width: 80%" />
        </el-form-item>
      </el-form>
      <el-row slot="footer" style="width: 100%">
        <el-col style="text-align: center">
          <el-button type="primary" size="mini" @click="addRole">确 定</el-button>
          <el-button size="mini" @click="close">取 消</el-button>
        </el-col>
      </el-row>
    </el-dialog>

    <!--权限弹出框-->
    <el-dialog title="分配权限" :visible.sync="showPermDialog" width="50%">
      <!-- 树形组件 -->
      <el-tree
        ref="permRef"
        check-strictly
        show-checkbox
        default-expand-all
        :default-checked-keys="rolePermissionList"
        :data="permissionList"
        :props="{label: 'name'}"
        node-key="id"
      />
      <!--slot="footer"可以将盒子放在底部-->
      <el-row slot="footer" style="width: 100%">
        <el-col style="text-align: center">
          <el-button type="primary" size="small" @click="assignPerm">确 定</el-button>
          <el-button size="small" @click="showPermDialog=false">取 消</el-button>
        </el-col>
      </el-row>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.container {
  padding: 20px;
  .app-container {
    padding: 20px;
    background-color: #fff;

  }
}
</style>
